Q ?= @
export Q

KPATH := $(PWD)
KINCLUDE := $(KPATH)/include
KERNEL := $(KPATH)/bin/kernel
export KPATH KINCLUDE
export KERNEL

ARCH ?= x86
CROSS ?= 
export ARCH

LD := ld
CC := $(CROSS)gcc
CCINCLUDE := -I"$(KINCLUDE)"
d := $(shell echo $(CCINCLUDE))
CFLAGS += -Wall -fstrength-reduce -fomit-frame-pointer -ffreestanding \
	  -fno-stack-protector -fno-stack-check -finline-functions \
	  -nostdinc -fno-builtin -c -D__$(ARCH)__=1 $(CCINCLUDE)
export LD CC CCINCLUDE
export CFLAGS

MAKEFLAGS += --no-print-directory -r
export MAKEFLAGS

FLOPPYIMG ?= bin/voidriddle.img

OBJS := src/kernel/arch/$(ARCH)/built.o src/kernel/built.o src/lib/built.o

PHONY:= all
all: $(KERNEL)
	@:

$(KERNEL): $(OBJS)
	@echo '   LD  $(KERNEL)'
	$(Q)$(LD) -T scripts/kernel-$(ARCH).ld -o $(KERNEL) $(OBJS)

%.o:
	$(Q)$(MAKE) $(MAKEFLAGS) -f scripts/Makefile.fbuild F=$(@D)

PHONY += test
test: $(KERNEL)
	$(Q)[ -f $(FLOPPYIMG) ] || \
		(printf "A floppy img is needed. Download? [Y/n] " && \
		read choice && [ "$$choice" != n ] && \
		wget http://voidriddle.googlecode.com/files/voidriddle.img \
		  -O $(FLOPPYIMG))
	$(Q)mcopy -o -i $(FLOPPYIMG) $(KERNEL) ::kernel
	$(Q)qemu -m 32 -fda $(FLOPPYIMG)

PHONY += all
clean:
	$(Q)$(MAKE) $(MAKEFLAGS) -f scripts/Makefile.fbuild F=src/kernel clean
	$(Q)$(MAKE) -f scripts/Makefile.fbuild F=src/kernel/arch/$(ARCH) clean
	$(Q)$(MAKE) -f scripts/Makefile.fbuild F=src/lib clean

.PHONY: $(PHONY)
